<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.assetName" placeholder="设备名称" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label>
            <ARangePicker
              v-model="searchFrom.purchaseDate"
              :placeholder="['购入日期', '购入日期']"
            />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 3])" type="outline" @click="openEdit('新增')">新增</AButton>
        </ASpace>
        <ASpace>
          <AButton type="primary" :loading="exportLoad" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        size="small"
        column-resizable
      >
        <template #columns>
          <ATableColumn title="设备名称" data-index="assetName" :width="170"></ATableColumn>
          <ATableColumn title="型号" data-index="assetModel" :width="255"></ATableColumn>
          <ATableColumn title="单位" data-index="assetUnit" :width="180"></ATableColumn>
          <ATableColumn title="数量" data-index="assetQty" :width="130"></ATableColumn>
          <ATableColumn title="购入日期" data-index="purchaseDate" :width="115" align="center">
            <template #cell="{ record }">
              <div v-if="record.purchaseDate">
                {{ dayjs(record.purchaseDate).format('YYYY-MM-DD') }}
              </div>
            </template>
          </ATableColumn>
          <ATableColumn title="预估金额" data-index="assetAmt" :width="100" align="center">
            <template #cell="{ record }">
              {{ `¥${formatPrice(record.assetAmt)}` }}
            </template>
          </ATableColumn>
          <ATableColumn title="备注" data-index="remark" :width="130" align="center">
          </ATableColumn>
          <ATableColumn title="操作" :width="145" align="center" fixed="right">
            <template #cell="{ record }">
              <ASpace>
                <AButton
                  v-if="record.assetName !== '汇总'"
                  type="primary"
                  size="mini"
                  @click="rowEvent(record, 'edit')"
                >
                  修改
                </AButton>
                <AButton
                  v-if="record.assetName !== '汇总'"
                  status="danger"
                  size="mini"
                  @click="rowEvent(record, 'del')"
                >
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="getTableData"
    ></EditPopupForm>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import { isAuth } from '@renderer/utils/auth'
import dayjs from 'dayjs'
import { Message, Modal } from '@arco-design/web-vue'
import { formatPrice } from '@renderer/utils/mixins'
import {
  delFixedAssets,
  FixedAssetsListSearch,
  FixedAssetsResItem,
  getFixedAssetsAllList,
  getFixedAssetsPageList
} from '@renderer/api/assetInventory'

const searchFrom = ref<FixedAssetsListSearch>({
  assetName: '',
  purchaseStartDate: '',
  purchaseEndDate: '',
  purchaseDate: [],
  assetType: 1
})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<FixedAssetsResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})

onMounted(() => {
  getTableData()
})

async function getTableData() {
  const [purchaseStartDate, purchaseEndDate] = searchFrom.value.purchaseDate! || []
  searchFrom.value.purchaseStartDate = purchaseStartDate
    ? dayjs(purchaseStartDate).format('YYYY-MM-DD')
    : ''
  searchFrom.value.purchaseEndDate = purchaseEndDate
    ? dayjs(purchaseEndDate).format('YYYY-MM-DD')
    : ''
  const res = await getFixedAssetsPageList({ ...searchFrom.value, ...pageParam })
  tableData.value = res.data.list
  pageParam.totalCount = res.data.totalCount!
}

function onSearch() {
  pageParam.currentPage = 1
  getTableData()
}

function onReset() {
  searchFrom.value = {
    assetName: '',
    purchaseStartDate: '',
    purchaseEndDate: '',
    purchaseDate: [],
    assetType: 1
  }
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}

function openEdit(title: string) {
  rowData.value = {
    customerId: undefined,
    assetId: '',
    assetName: '',
    assetModel: '',
    assetUnit: '',
    assetQty: 0,
    purchaseDate: '',
    assetAmt: 0,
    depreciationYear: 0,
    depreciationResidualValue: 0,
    assetType: 1,
    remark: ''
  }
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref<FixedAssetsResItem>()

function rowEvent(row: FixedAssetsResItem, type: string) {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delFixedAssets({ assetId: row.assetId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break

    default:
      break
  }
}

const exportLoad = ref(false)

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  exportLoad.value = true
  const headerData = [
    { title: '设备名称', value: 'assetName', width: 180 },
    { title: '型号', value: 'assetModel', width: 180 },
    { title: '单位', value: 'assetUnit' },
    { title: '数量', value: 'assetQty' },
    { title: '购入日期', value: 'purchaseDate' },
    { title: '预估金额', value: 'assetAmt' },
    { title: '备注', value: 'remark', width: 180 }
  ]
  let excelData: FixedAssetsResItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '其他固定资产'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        if (searchFrom.value.purchaseDate) {
          ;[searchFrom.value.purchaseStartDate, searchFrom.value.purchaseEndDate] =
            searchFrom.value.purchaseDate!
          searchFrom.value.purchaseStartDate = dayjs(searchFrom.value.purchaseStartDate).format(
            'YYYY-MM-DD'
          )
          searchFrom.value.purchaseEndDate = dayjs(searchFrom.value.purchaseEndDate).format(
            'YYYY-MM-DD'
          )
        }
        const res = await getFixedAssetsAllList(searchFrom.value)
        excelData = res.data.list
      }
      break
    case 'template':
      fileTitle = '其他固定资产导入模板'
      excelData = [
        {
          assetName: '小米笔记本',
          assetModel: '笔记本',
          assetUnit: '台',
          assetQty: 0,
          purchaseDate: '2025-02-06',
          assetAmt: 0,
          depreciationYear: 0,
          depreciationResidualValue: 0,
          assetType: 1,
          remark: ''
        }
      ]
      break

    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle)
    exportLoad.value = false
  })
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
